<template>
  <div class="chat-container">
    <div class="chat-header">
      <h2>Netty聊天室</h2>
      <div class="connection-status" :class="{ connected: isConnected }">
        {{ isConnected ? '已连接' : '未连接' }}
      </div>
    </div>
    
    <div class="chat-messages" ref="messagesContainer">
      <div 
        v-for="(message, index) in messages" 
        :key="index" 
        class="message"
        :class="getMessageClass(message)"
      >
        <!-- 系统消息 -->
        <div v-if="message.type === 'system'" class="system-message-content">
          {{ message.content }}
        </div>
        
        <!-- 聊天消息 -->
        <div v-else>
          <div class="message-info">
            <div class="user-info">
              <div class="avatar" :style="getAvatarStyle(message.user)">{{ getAvatarText(message.user) }}</div>
              <span class="message-user">{{ getUserDisplayName(message.user) }}</span>
            </div>
            <span class="message-time">{{ formatTime(message.time) }}</span>
          </div>
          <div class="message-content">{{ message.content }}</div>
        </div>
      </div>
    </div>
    
    <div class="chat-input">
      <input 
        v-model="newMessage" 
        @keyup.enter="sendMessage" 
        placeholder="输入消息..." 
        :disabled="!isConnected"
      />
      <button @click="sendMessage" :disabled="!isConnected || !newMessage.trim()">发送</button>
    </div>
  </div>
</template>

<script>
export default {
  name: 'ChatRoom',
  data() {
    return {
      ws: null,
      isConnected: false,
      newMessage: '',
      messages: [],
      // 存储用户颜色映射
      userColors: new Map(),
      // 存储用户昵称映射
      userNames: new Map(),
      // 中文姓氏列表
      chineseSurnames: [
        '赵', '钱', '孙', '李', '周', '吴', '郑', '王', '冯', '陈', 
        '褚', '卫', '蒋', '沈', '韩', '杨', '朱', '秦', '尤', '许',
        '何', '吕', '施', '张', '孔', '曹', '严', '华', '金', '魏',
        '陶', '姜', '戚', '谢', '邹', '喻', '柏', '水', '窦', '章',
        '云', '苏', '潘', '葛', '奚', '范', '彭', '郎', '鲁', '韦',
        '昌', '马', '苗', '凤', '花', '方', '俞', '任', '袁', '柳',
        '酆', '鲍', '史', '唐', '费', '廉', '岑', '薛', '雷', '贺',
        '倪', '汤', '滕', '殷', '罗', '毕', '郝', '邬', '安', '常',
        '乐', '于', '时', '傅', '皮', '卞', '齐', '康', '伍', '余',
        '元', '卜', '顾', '孟', '平', '黄', '和', '穆', '萧', '尹'
      ],
      // 中文名字列表
      chineseNames: [
        '伟', '芳', '娜', '敏', '静', '丽', '强', '磊', '军', '洋',
        '勇', '艳', '杰', '娟', '涛', '明', '超', '秀英', '霞', '平',
        '刚', '桂英', '龙', '飞', '华', '玉兰', '红', '丽娟', '波', '军',
        '文', '建', '利', '娟', '磊', '国', '娜', '建军', '华', '丽华',
        '荣', '鑫', '宁', '婷', '雪', '晶', '丹', '莹', '颖', '霞',
        '慧', '倩', '琳', '嘉', '怡', '婕', '萌', '慧', '瑶', '璐',
        '晨', '涵', '诗', '彤', '欣', '洁', '婉', '莉', '琴', '蓉'
      ]
    }
  },
  mounted() {
    this.connect()
  },
  beforeUnmount() {
    if (this.ws) {
      // 移除事件监听器
      this.ws.onclose = null;
      this.ws.onerror = null;
      this.ws.onmessage = null;
      this.ws.onopen = null;
      // 关闭连接
      this.ws.close();
    }
  },
  methods: {
    connect() {
      // 连接到Netty WebSocket服务器
      this.ws = new WebSocket('ws://localhost:8080/ws')
      
      this.ws.onopen = () => {
        console.log('WebSocket连接已建立')
        this.isConnected = true
        this.addSystemMessage('已连接到聊天服务器')
      }
      
      this.ws.onmessage = (event) => {
        try {
          const data = JSON.parse(event.data)
          if (data.type === 'system') {
            this.addSystemMessage(data.message)
          } else if (data.type === 'chat') {
            this.addChatMessage(data.user, data.message)
          }
        } catch (e) {
          console.error('解析消息失败:', e)
          this.addSystemMessage(event.data)
        }
      }
      
      this.ws.onclose = () => {
        console.log('WebSocket连接已关闭')
        this.isConnected = false
        // 自动重连
        setTimeout(() => {
          this.addSystemMessage('与服务器的连接已断开，尝试重新连接...')
          this.connect()
        }, 3000)
      }
      
      this.ws.onerror = (error) => {
        console.error('WebSocket错误:', error)
        this.addSystemMessage('连接发生错误')
      }
    },
    
    sendMessage() {
      if (!this.newMessage.trim() || !this.isConnected) return
      
      this.ws.send(this.newMessage.trim())
      this.newMessage = ''
    },
    
    addSystemMessage(content) {
      this.messages.push({
        type: 'system',
        user: '系统',
        content: content,
        time: new Date()
      })
      this.$nextTick(this.scrollToBottom)
    },
    
    addChatMessage(user, content) {
      this.messages.push({
        type: 'chat',
        user: user,
        content: content,
        time: new Date()
      })
      this.$nextTick(this.scrollToBottom)
    },
    
    getMessageClass(message) {
      return {
        'system-message': message.type === 'system',
        'user-message': message.type === 'chat'
      }
    },
    
    formatTime(date) {
      return date.toLocaleTimeString('zh-CN', { 
        hour: '2-digit', 
        minute: '2-digit' 
      })
    },
    
    scrollToBottom() {
      const container = this.$refs.messagesContainer
      container.scrollTop = container.scrollHeight
    },
    
    // 获取用户头像背景色
    getAvatarStyle(user) {
      // 系统消息特殊处理
      if (user === '系统') {
        return { backgroundColor: '#6c757d' };
      }
      
      if (!this.userColors.has(user)) {
        // 为新用户生成随机颜色
        const colors = [
          '#FF6B6B', '#4ECDC4', '#45B7D1', '#FFBE0B', '#FB5607', 
          '#8338EC', '#3A86FF', '#06D6A0', '#118AB2', '#073B4C',
          '#EF476F', '#FFD166', '#06D6A0', '#118AB2', '#073B4C',
          '#7209B7', '#3A86FF', '#F15BB5', '#9B5DE5', '#00BBF9'
        ];
        const randomColor = colors[Math.floor(Math.random() * colors.length)];
        this.userColors.set(user, randomColor);
      }
      
      return {
        backgroundColor: this.userColors.get(user)
      };
    },
    
    // 获取头像显示文字（使用中文姓氏）
    getAvatarText(user) {
      if (user === '系统') return '系';
      
      // 获取用户显示名称
      const displayName = this.getUserDisplayName(user);
      // 只返回姓氏（第一个字符）
      return displayName.charAt(0);
    },
    
    // 获取用户显示名称
    getUserDisplayName(user) {
      // 系统消息直接返回
      if (user === '系统') return '系统';
      
      // 检查是否已经有昵称
      if (!this.userNames.has(user)) {
        // 生成随机中文名
        const surname = this.chineseSurnames[Math.floor(Math.random() * this.chineseSurnames.length)];
        const name = this.chineseNames[Math.floor(Math.random() * this.chineseNames.length)];
        const fullName = surname + name;
        this.userNames.set(user, fullName);
      }
      
      return this.userNames.get(user);
    }
  }
}
</script>

<style scoped>
.chat-container {
  max-width: 800px;
  margin: 0 auto;
  border: 1px solid #ddd;
  border-radius: 8px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  height: 80vh;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.chat-header {
  background-color: #42b983;
  color: white;
  padding: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.connection-status {
  font-size: 14px;
  padding: 4px 8px;
  border-radius: 4px;
  background-color: #ff6b6b;
}

.connection-status.connected {
  background-color: #42b983;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
  background-color: #f8f9fa;
}

.message {
  margin-bottom: 12px;
  padding: 10px;
  border-radius: 6px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.system-message {
  background-color: #f8f9fa;
  border: none;
  box-shadow: none;
  padding: 4px 0;
}

.user-message {
  background-color: #ffffff;
  border-left: 4px solid #42b983;
}

.system-message-content {
  text-align: center;
  font-size: 12px;
  color: #6c757d;
  padding: 4px 0;
}

.message-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 4px;
  font-size: 12px;
  color: #6c757d;
}

.user-info {
  display: flex;
  align-items: center;
}

.avatar {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-weight: bold;
  font-size: 12px;
  margin-right: 8px;
  flex-shrink: 0; /* 防止头像在小屏幕上变形 */
}

.message-user {
  font-weight: bold;
}

.message-content {
  text-align: left;
  word-wrap: break-word;
}

.chat-input {
  display: flex;
  padding: 16px;
  background-color: white;
  border-top: 1px solid #ddd;
}

.chat-input input {
  flex: 1;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  margin-right: 8px;
  font-size: 14px;
}

.chat-input button {
  padding: 10px 20px;
  background-color: #42b983;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.chat-input button:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.chat-input input:disabled {
  background-color: #f5f5f5;
}
</style>